package com.gfl.trivialrestclient.controllers.validators;

import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import com.gfl.trivialrestclient.model.Product;

public class ProductValidator implements Validator {

	@Override
	public boolean supports(Class<?> clazz) {
		return Product.class.equals(clazz);
	}

	@Override
	public void validate(Object obj, Errors e) {
		ValidationUtils.rejectIfEmpty(e, "name", "name.empty", "Empty name");
		Product p = (Product) obj;
		if (p.getUnits() < 0) {
			e.rejectValue("units", "negativevalue", "Negative value");
		} else if (p.getUnits() == 0) {
			e.rejectValue("units", "zerrovalue", "Zerror value");
		}
		if (p.getWeight() < 0) {
			e.rejectValue("weight", "negativevalue", "Negative value");
		}
	}

}
